<template>
  <div class="">
    <a class="submit-btn" style="background-color:#badeff;border: 1px solid #badeff;" @click="format">格式化</a>
    <a class="submit-btn" @click="runcode">提交运行</a>
    <a class="app-btn" @click="submitApp">确认应用</a>
    <a class="app-btn" @click="handleAdd">上传到自定义组件库</a>
     <i class="el-icon-question" style="font-size:20px" @click="openTip()"></i>
    <div class="tip" style="" v-if="tip">
      <div>可直接获取绑定参数：requestParameters，接口返回数据：dataValue</div>
      <div>其中dataValue仅在确认应用后生效</div>
      
    </div>
    <div id="main_container">
      <div id="core" class="core core_margin1">
        <div class="editorSet clearfix">
          <div>
            <div class="editor">
              <span class="label">javascript</span>
              <div ref="ace" class="edit-area"></div>
            </div>
            <div ref="customCanvas" class="editor">
              <run-code :customOption='cusOption'></run-code>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 添加或修改自定义组件库对话框 -->
    <el-dialog title="自定义组件添加" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="图表名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入图表名称" />
        </el-form-item>
        
        <el-form-item label="所属图表">
          <el-select v-model="form.graph" placeholder="请选择所属图表">
            <el-option
              v-for="dict in graphOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属组件">
          <el-select v-model="form.component" placeholder="请选择所属组件">
            <el-option
              v-for="dict in componentOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="标签" prop="tag">
          <el-input v-model="form.tag" placeholder="请输入标签" />
        </el-form-item>
        
        <el-form-item label="是否公开">
          <el-radio-group v-model="form.isOpen">
            <el-radio
              v-for="dict in isOpenOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
        
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>
<script>
import ace from "ace-builds";
import "ace-builds/webpack-resolver"; // 在 webpack 环境中使用必须要导入
import "ace-builds/src-noconflict/theme-monokai"; // 默认设置的主题
import "ace-builds/src-noconflict/mode-javascript"; // 默认设置的语言模式
import {js_beautify} from '../../../../../cms/js/beautify.js'
// 引入html2canvas
import html2canvas from 'html2canvas';

import VueEvent from '@/views/tool/datav/VueEvent'

import RunCode from '@/views/tool/datav/components/config/runcode/RunCode'

import { addCustomchart, updateCustomchart } from "@/api/tool/datav/customchart";

export default {
  props: ["customOption"],
  components: {
    RunCode,
    html2canvas
  },
  data() {
    return {
      aceEditor: null,
      themePath: "ace/theme/monokai", // 不导入 webpack-resolver，该模块路径会报错
      modePath: "ace/mode/javascript", // 同上
      cusOption: this.customOption,
      open: false,
      // 所属图表字典
      graphOptions: [],
      // 所属组件字典
      componentOptions: [],
      // 是否公开字典
      isOpenOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        chartOption: undefined,
        graph: undefined,
        component: undefined,
        tag: undefined,
        isOpen: undefined,
        status: undefined,
      },
      // 表单参数
      form: {
        isOpen:"N"
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: "图表名称不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "大屏状态（0正常 1停用 2已发布）不能为空", trigger: "blur" }
        ],
      },
      tip:false,//提示框
    };
  },
  created() {
    this.getDicts("datav_graph").then(response => {
      this.graphOptions = response.data;
    });
    this.getDicts("datav_component").then(response => {
      this.componentOptions = response.data;
    });
    this.getDicts("sys_yes_no").then(response => {
      this.isOpenOptions = response.data;
    });
  },
  mounted() {
    this.$nextTick(() => {
      this.aceEditor = ace.edit(this.$refs.ace, {
        maxLines: 20, // 最大行数，超过会自动出现滚动条
        minLines: 10, // 最小行数，还未到最大行数时，编辑器会自动伸缩大小
        fontSize: 14, // 编辑器内字体大小
        theme: this.themePath, // 默认设置的主题
        mode: this.modePath, // 默认设置的语言模式
        tabSize: 4, // 制表符设置为 4 个空格大小
      });
      this.aceEditor.setValue(this.customOption);
    });
  },
  methods: {
    runcode() {
      this.cusOption = this.aceEditor.getValue();
    },
    submitApp() {
      this.$emit("submitCustom", JSON.parse(JSON.stringify( this.cusOption )));
    },
    upload() {
      
    },
    // 所属图表字典翻译
    graphFormat(row, column) {
      return this.selectDictLabel(this.graphOptions, row.graph);
    },
    // 所属组件字典翻译
    componentFormat(row, column) {
      return this.selectDictLabel(this.componentOptions, row.component);
    },
    // 是否公开字典翻译
    isOpenFormat(row, column) {
      return this.selectDictLabel(this.isOpenOptions, row.isOpen);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        chartOption: undefined,
        graph: undefined,
        component: undefined,
        tag: undefined,
        thumbnail: undefined,
        isOpen: "N",
        status: "0",
        delFlag: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        remark: undefined
      };
      this.resetForm("form");
    },
    
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
    },
    
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {

          this.form.chartOption = this.aceEditor.getValue();
          // 第一个参数是需要生成截图的元素,第二个是自己需要配置的参数,宽高等
          html2canvas(this.$refs.customCanvas, {
            backgroundColor: null,
    　　　　 useCORS: true // 如果截图的内容里有图片,可能会有跨域的情况,加上这个参数,解决文件跨域问题
          }).then((canvas) => {
            let url = canvas.toDataURL('image/png')
            //console.log(url);
            this.form.thumbnail = url;
            
              addCustomchart(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("添加成功");
                  this.open = false;
                } else {
                  this.msgError(response.msg);
                }
              });
          })
          
        }
      });
    },
    openTip(){
      this.tip = !this.tip;
    },
    format(){
      let val = this.aceEditor.getValue();
      //格式化
      var jsbOpts = { 
 
          indent_size : 4
      
      }; 
      this.aceEditor.setValue(js_beautify(val, jsbOpts))
    }
  },
};
</script>
<style scoped>

@media screen and (min-width: 960px) {
  .editorSet {
    width: 100%;
  }
  .editorSet .editor {
    height: 450px;
    width: 48%;
    overflow-y: hidden;
    background-color: rgb(44, 52, 55);
    float: left;
  }
}

@media screen and (max-width: 959px) {
  .editorSet {
    width: 100%;
  }
  .editorSet .editor {
    height: 450px;
    width: 100%;
    overflow-y: hidden;
    background-color: rgb(44, 52, 55);
  }
}

.NightTheme .editorSet .editor {
  -webkit-box-shadow: inset 0 1px 3px rgb(22, 26, 27);
  -moz-box-shadow: inset 0 1px 3px rgb(22, 26, 27);
  box-shadow: inset 0 1px 3px rgb(22, 26, 27);
}

.label {
  background: rgba(230, 230, 230, 0.5);
  height: 20px;
  padding: 0 6px;
  line-height: 20px;
  z-index: 999;
  text-align: center;
  font-size: 12px;
  color: #bbb;
  border-radius: 3px;
}

.editor iframe {
  border: 0 !important;
  min-height: 100px;
  min-width: 100px;
  height: 100%;
  width: 100%;
}

.submit-btn {
  color: #fff;
  background-color: #67c23a;
  display: inline-block;
  line-height: 1;
  white-space: nowrap;
  cursor: pointer;
  border: 1px solid #67c23a;
  -webkit-appearance: none;
  text-align: center;
  box-sizing: border-box;
  outline: none;
  margin: 0;
  transition: 0.1s;
  -moz-user-select: none;
  -webkit-user-select: none;
  -ms-user-select: none;
  padding: 12px 20px;
  font-size: 14px;
  border-radius: 4px;
  margin-bottom: 2px;
}

.app-btn {
  color: #fff;
  background-color: #0144fd;
  display: inline-block;
  line-height: 1;
  white-space: nowrap;
  cursor: pointer;
  border: 1px solid #0144fd;
  -webkit-appearance: none;
  text-align: center;
  box-sizing: border-box;
  outline: none;
  margin: 0;
  transition: 0.1s;
  -moz-user-select: none;
  -webkit-user-select: none;
  -ms-user-select: none;
  padding: 12px 20px;
  font-size: 14px;
  border-radius: 4px;
  margin-bottom: 2px;
}

.edit-area {
  height: 100%;
}
.tip{
  position: absolute;
  top:40px;
  left:510px;
  width:320px;
  height:auto;
  line-height: 24px;
  padding: 10px;
  z-index:99;
  background-color: #6c717514;
  text-align: left;
  font-family: "微软雅黑";
}
</style>